package com.cssnj.portal.web.login;

import com.cssnj.portal.domain.common.UserInfo;
import com.cssnj.portal.domain.user.SsoVO;
import com.cssnj.portal.service.login.LoginService;
import com.cssnj.portal.utils.PortalUntil;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.predictech.framework.domain.common.JsonRequest;
import io.predictech.framework.domain.common.JsonResponse;
import io.predictech.framework.domain.constants.SysConstants;
import io.predictech.framework.domain.exception.BaseException;
import io.predictech.framework.utility.IPHelper;
import io.predictech.framework.utility.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;


@Controller
public class LoginController {


    @Autowired
    private LoginService loginService;

    @Autowired
    Environment environment;

    @RequestMapping(value = {"/", "/login.c"})
    public ModelAndView login(HttpServletRequest request) {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            PortalUntil.logger().info("已登录,转入首页");
            return new ModelAndView("redirect:/home.do");
        }
        PortalUntil.logger().info("未登录,转入登录页");
        return new ModelAndView("login/login");
    }

    /**
     * 金三单点登录
     *
     * @param request,token
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = {"/JsSsoLogin.c"})
    public ModelAndView JsSsoLogin(HttpServletRequest request, String token) throws BaseException {
        PortalUntil.logger().info("进入JsSsoLogin方法");
        if (SecurityUtils.getSubject().isAuthenticated()) {
            PortalUntil.logger().info("已存在回话，即将转入首页");
            return new ModelAndView("redirect:/home.do");
        }
        PortalUntil.logger().info("----金三单点登录开始----");
        if (null == token || "".equals(token)) {
            PortalUntil.logger().info("单点登录信息不全，本次登录失败！");
            request.getSession().setAttribute("code", "SSO1001");
            request.getSession().setAttribute("msg", "单点登录信息不全，本次登录失败！");
            return new ModelAndView("redirect:/login.c");
        }
        SsoVO vo = null;
        try {
            PortalUntil.logger().info("解密前:" + token);
            String jmh = com.css.aqrz.util.DesbaseTool.decrypt(token);
            PortalUntil.logger().info("解密后:" + jmh);
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            vo = mapper.readValue(jmh, SsoVO.class);
            PortalUntil.logger().info("解密完成");
            JsonRequest jsonRequest = new JsonRequest();

            String swjgdm = vo.getSwjgdm();
            if (swjgdm.startsWith("2")) {
                jsonRequest.getReqData().put("swrysfDm", "0," + vo.getSwrysfdm());
            } else {
                jsonRequest.getReqData().put("swrysfDm", "1," + vo.getSwrysfdm());
            }
            jsonRequest.setServiceName("loginService");
            jsonRequest.setHandleCode("loginInBySwsf");
            jsonRequest.getReqData().put("ip", IPHelper.getIPAddress(request));
            JsonResponse jsonResponse = loginService.execute(jsonRequest);
            if (SysConstants.SUCESS_CODE.equals(jsonResponse.getCode())) {
                if (null != jsonResponse.getRepData().get("isGs")) {
                    request.getSession().setAttribute("isGs", jsonResponse.getRepData().get("isGs"));
                }
                UserInfo userInfo = (UserInfo) jsonResponse.getRepData().get("userInfo");
                saveSession(userInfo, request);
                return new ModelAndView("redirect:/home.do");
            }
            request.getSession().setAttribute("code", jsonResponse.getCode());
            request.getSession().setAttribute("msg", jsonResponse.getMsg());
            return new ModelAndView("redirect:/login.c");

        } catch (Exception e) {
            e.printStackTrace();
            PortalUntil.logger().info(e.getMessage());
            request.getSession().setAttribute("code", "SSO1002");
            request.getSession().setAttribute("msg", "单点登录出现异常：" + e.getMessage());
            return new ModelAndView("redirect:/login.c");
        }

    }


    @RequestMapping(value = {"/doLogout.do"})
    public ModelAndView doLogout(HttpServletRequest request) {
        clearTempSession(request);
        return new ModelAndView("redirect:/login.c");
    }

    @RequestMapping(value = {"/loginIn.c"})
    public ModelAndView loginIn(HttpServletRequest request, String userName, String passWord) throws BaseException, SQLException {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            PortalUntil.logger().info("已登录,转入首页");
            return new ModelAndView("redirect:/home.do");
        }
        clearTempSession(request);
        JsonRequest jsonRequest = new JsonRequest();
        jsonRequest.setServiceName("loginService");
        jsonRequest.setHandleCode("loginIn");
        jsonRequest.getReqData().put("userName", userName);
        jsonRequest.getReqData().put("passWord", passWord.toUpperCase());
        jsonRequest.getReqData().put("ip", IPHelper.getIPAddress(request));
        JsonResponse jsonResponse = loginService.execute(jsonRequest);
        if (SysConstants.SUCESS_CODE.equals(jsonResponse.getCode())) {
            if (null != jsonResponse.getRepData().get("isGs")) {
                request.getSession().setAttribute("isGs", jsonResponse.getRepData().get("isGs"));
            }
            if (null != jsonResponse.getRepData().get("swrysfList")) {
                request.getSession().setAttribute("swrysfList", jsonResponse.getRepData().get("swrysfList"));
                return new ModelAndView("redirect:/login.c");
            }
            UserInfo userInfo = (UserInfo) jsonResponse.getRepData().get("userInfo");
            saveSession(userInfo, request);
            return new ModelAndView("redirect:/home.do");
        }
        request.getSession().setAttribute("code", jsonResponse.getCode());
        request.getSession().setAttribute("msg", jsonResponse.getMsg());
        return new ModelAndView("redirect:/login.c");
    }

    /**
     * 选择身份登陆
     *
     * @param request
     * @return
     * @throws BaseException
     * @throws SQLException
     */
    @RequestMapping(value = {"/loginInBySwsf.c"})
    public ModelAndView loginInBySwsf(HttpServletRequest request) throws BaseException, SQLException {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            PortalUntil.logger().info("已登录,转入首页");
            return new ModelAndView("redirect:/home.do");
        }
        List<Map<String, Object>> swrysfList = (List<Map<String, Object>>) request.getSession().getAttribute("swrysfList");
        if (null == swrysfList) {
            request.getSession().setAttribute("code", "W1001");
            request.getSession().setAttribute("msg", "用户名或密码错误");
            return new ModelAndView("redirect:/login.c");
        }
        boolean check = false;
        String swrysfDm = request.getParameter("swrysf_dm");
        for (int i = 0; i < swrysfList.size(); i++) {
            if (swrysfDm.equals(swrysfList.get(i).get("SWRYSF_DM"))) {
                check = true;
                break;
            }
        }
        if (check == false) {
            request.getSession().removeAttribute("swrysfList");
            request.getSession().setAttribute("code", "W1001");
            request.getSession().setAttribute("msg", "用户名或密码错误");
            return new ModelAndView("redirect:/login.c");
        }
        JsonRequest jsonRequest = new JsonRequest();
        jsonRequest.setServiceName("loginService");
        jsonRequest.setHandleCode("loginInBySwsf");
        jsonRequest.getReqData().put("swrysfDm", swrysfDm);
        //jsonRequest.getReqData().put("isGs", request.getSession().getAttribute("isGs"));
        jsonRequest.getReqData().put("ip", IPHelper.getIPAddress(request));
        JsonResponse jsonResponse = loginService.execute(jsonRequest);
        if (SysConstants.SUCESS_CODE.equals(jsonResponse.getCode())) {
            UserInfo userInfo = (UserInfo) jsonResponse.getRepData().get("userInfo");
            saveSession(userInfo, request);
            String isGs = (String) jsonResponse.getRepData().get("isGs");
            request.getSession().setAttribute("isGs", jsonResponse.getRepData().get("isGs"));
            return new ModelAndView("redirect:/home.do");
        }
        request.getSession().setAttribute("code", jsonResponse.getCode());
        request.getSession().setAttribute("msg", jsonResponse.getMsg());
        return new ModelAndView("redirect:/login.c");
    }


    private void clearTempSession(HttpServletRequest request) {
        request.getSession().removeAttribute("code");
        request.getSession().removeAttribute("msg");
        request.getSession().removeAttribute("swrysfList");
        request.getSession().removeAttribute("isGs");
    }


    /**
     * 保存session 注册
     *
     * @param userinfo
     * @return
     */
    private JsonResponse saveSession(UserInfo userinfo, HttpServletRequest servletRequest) {
        JsonResponse jsonResponse = new JsonResponse();
        Subject subject = SecurityUtils.getSubject();
        try {
            String userJson = StringUtil.getBaseObjectMapper().writeValueAsString(userinfo);
            UsernamePasswordToken token = new UsernamePasswordToken(userJson, "1");
            subject.login(token);
            token.clear();
            clearTempSession(servletRequest);
        } catch (Exception e) {
            jsonResponse.setCode("W1001");
            jsonResponse.setMsg("抱歉，系统暂时无法访问,请稍后再试");
        }
        return jsonResponse;
    }

}
